const express = require('express')
const router = express.Router()
const Employment = require('../models/Employment')
const { markFileAsReferenced, unmarkFileReference } = require('../middlewares/fileReference')
const authMiddleware = require('../middlewares/auth')
// 创建岗位
router.post('/addEmployment', authMiddleware(), async (req, res) => {
  try {
    // 添加日期格式验证
    if (!/^\d{4}-\d{2}-\d{2}$/.test(req.body.postDate)) {
      return res.status(400).json({ message: '日期格式应为YYYY-MM-DD' })
    }
    const { postDate, fileId, companyName, position, description, studentInfoList, isFilled, isSuccessCase } = req.body

    const newPost = new Employment({
      postDate,
      files: fileId,
      companyName,
      position,
      description,
      studentInfoList: studentInfoList || [],
      isFilled,
      isSuccessCase: isSuccessCase || 0
    })

    const savedPost = await newPost.save()
    await markFileAsReferenced(fileId)

    res.status(201).json(savedPost)
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 获取所有岗位
router.get('/queryEmployment', async (req, res) => {
  try {
    const { year, postId, companyName, isFilled, pageNum = 1, pageSize = 10 } = req.query
    const filter = {}
    const options = {
      skip: (pageNum - 1) * pageSize,
      limit: parseInt(pageSize),
      sort: { postDate: -1 }
    }

    // 按ID精确查询
    if (postId) {
      filter._id = postId
    }

    // 按年份筛选
    if (year) {
      filter.year = parseInt(year)
    }
    if (isFilled) {
      filter.isFilled = parseInt(isFilled)
    }
    if (companyName) {
      // 模糊查询
      filter.companyName = { $regex: companyName, $options: 'i' }
    }
    const [posts, total] = await Promise.all([
      Employment.find(filter).populate('files').skip(options.skip).limit(options.limit).sort(options.sort),
      Employment.countDocuments(filter)
    ])

    res.json({
      data: posts,
      pageNum: parseInt(pageNum),
      pageSize: parseInt(pageSize),
      totalPages: Math.ceil(total / options.limit),
      total,
      message: '查询成功'
    })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

// 更新岗位
router.post('/updateEmployment', authMiddleware(), async (req, res) => {
  try {
    const { fileId, postId, postDate, companyName, position, description, studentInfoList, isFilled, isSuccessCase } = req.body
    // 添加日期格式验证
    if (postDate && !/^\d{4}-\d{2}-\d{2}$/.test(postDate)) {
      return res.status(400).json({ message: '日期格式应为YYYY-MM-DD' })
    }
    const post = await Employment.findById(postId)
    if (!post) return res.status(404).json({ message: '岗位不存在' })

    // 处理图片更新
    if (fileId && fileId !== post.files.toString()) {
      await unmarkFileReference(post.files)
      await markFileAsReferenced(fileId)
      post.files = fileId
    }
    // 处理年份
    // 如果更新了开始日期，则更新年份
    if (postDate) {
      const [year, month, day] = postDate.split('-')
      post.year = new Date(Date.UTC(year, month - 1, day)).getUTCFullYear()
    }
    Object.assign(post, {
      postDate,
      companyName,
      position,
      description,
      studentInfoList,
      isFilled,
      isSuccessCase
    })
    const updatedPost = await post.save()

    res.json(updatedPost)
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 删除岗位
router.post('/deleteEmployment', authMiddleware(), async (req, res) => {
  try {
    const post = await Employment.findByIdAndDelete(req.body.postId)
    if (!post) return res.status(404).json({ message: '岗位不存在' })

    await unmarkFileReference(post.files)

    res.json({ message: '岗位已删除' })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

module.exports = router
